#pragma once

#include "Log.hpp"
#include "Thread.hpp"
#include <vector>
#include <queue>
#include "Mutex.hpp"
#include "Cond.hpp"

namespace ThreadPoolModule
{
    using namespace CondModule;
    using namespace MutexModule;
    using namespace ThreadModlue;
    using namespace LogModule;
    static const int gnum = 15; // 线程池中线程的个数

    template <typename T>
    class ThreadPool
    {
    private:
        void WakeUpAllThread()
        {
            LockGuard lockguard(_mutex);
            if (_sleepernum > 0)
                _cond.Broadcast();
            LOG(LogLevel::INFO) << " 唤醒所有线程";
        }

        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << " 唤醒一个线程";
        }

        ThreadPool(int num = gnum) : _num(num), _isrunning(false)
        {
            for (int i = 0; i < _num; i++)
            {
                _thread.emplace_back([this]()
                                     { HandlerTask(); });
            }
        }

        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    public:
        static ThreadPool<T> *GetIntance()
        {
            if (inc == nullptr)
            {
                LockGuard lockguard(_lock);
                LOG(LogLevel::DEBUG) << "获取单例......";
                if (inc == nullptr)
                {

                    LOG(LogLevel::DEBUG) << " 首次使用单例，创建之......";
                    inc = new ThreadPool<T>();
                    inc->Start();
                }
            }
            return inc;
        }

        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (int i = 0; i < _num; i++)
            {
                _thread[i].Start();
                // LOG(LogLevel::INFO) << " 线程" << _thread[i].Name() << " 启动";
            }
        }

        void Stop()
        {
            // 线程退出的时候，内部的任务，应该被完全取完
            if (!_isrunning)
                return;
            _isrunning = false;
            for (int i = 0; i < _num; i++)
            {
                _thread[i].Stop();
            }

            // 唤醒所有线程
            WakeUpAllThread();
        }

        void Join()
        {
            for (int i = 0; i < _num; i++)
            {
                _thread[i].Join();
            }
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    // 1. a.队列是否为空 b.线程池没有退出
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }
                    // 当任务队列不为空就会继续运行将任务处理完。
                    if (!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << " 线程退出，线程退出&&任务队列为空";
                        break;
                    }
                    // 一定有任务
                    t = _taskq.front(); // 从q中获取任务，任务已经是线程私有的了！！！
                    _taskq.pop();
                }
                t(); // 处理任务，需要在临界区内部处理吗？不用因为线程私有了
            }
        }

        bool Enqueue(const T &in)
        {
            if (_isrunning)
            {
                LockGuard lockguard(_mutex);
                _taskq.push(in);
                if (_thread.size() - _sleepernum == 0)
                    WakeUpOne();
                return true;
            }
            return false;
        }

        ~ThreadPool()
        {
        }

    private:
        std::vector<Thread> _thread;
        int _num; // 线程池中线程的个数

        std::queue<T> _taskq;
        Mutex _mutex;
        Cond _cond;
        bool _isrunning;
        int _sleepernum = 0; // 睡眠的线程数

        static ThreadPool<T> *inc; // 单例指针
        static Mutex _lock;
    };

    template <typename T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;
    template <typename T>
    Mutex ThreadPool<T>::_lock;
}